package vn.com.tiz.DocumentZ.utils;

import java.util.ArrayList;

import vn.com.tiz.core.AppSetting;

import android.text.TextPaint;
import android.util.Log;
import android.widget.TextView;

public class StringTools {

	
	
	public StringTools() {

	}
	/**
	 * TrungTT
	 * @param text : chuoi text can wrap
	 * @param displayWidth : do rong ma text can wrap
	 * @param txv : TextView tham khao de lay chinh xac textwidth
	 * @return
	 */
	public static ArrayList<String> wrapText(String text,int displayWidth,TextPaint textpaint){
		int start = 0;
		int end  = 0;
		ArrayList<String> result = new ArrayList<String>();
		String temp = "";
		for(int i=0;i<text.length();i++){
			end = i;
			float w = textpaint.measureText(text, start, end);
			if(w >= displayWidth){
				try {
					temp = text.substring(start, end);
					char lastchar = temp.charAt(temp.length()-1);
					if(lastchar == ' '){
						temp = text.substring(start, end);
						result.add(temp);
						start = end;
					}else{
						int lastWord = end;					
						for(int j=(temp.length()-1);j>0;j--){
							if(temp.charAt(j) == ' '){
								lastWord = j;
								break;
							}
						}
						temp  = temp.substring(0, lastWord);
						result.add(temp);
						start += lastWord;
						if(end == (text.length()-1)){
							temp = text.substring(start);
							result.add(temp);
							break;
						}
					}
				} catch (Exception e) {
					Log.e("TrungTT","end:"+end+" len:"+text.length());
				}
				
				
			}else{
				if(i == (text.length()-1)){				
					temp = text.substring(start);
					result.add(temp);
				}
			}
		}
		return result;
	}

	/**
	 * TrungTT
	 * Description	: 
	 * @param lines
	 */
	public static ArrayList<String> parseIntoPages(ArrayList<String> lines,int maxLine,int widthDisplay,TextPaint textpaint){
		ArrayList<String> pages = new ArrayList<String>();
		String strPage = "";
		int count = 0;
		
		for(String str:lines){
			if(str.trim().length() == 0){
				count++;
			}else{
			
				ArrayList<String> arr = wrapText(str,widthDisplay,textpaint);			
				for(String s:arr){
					
					strPage +=s;
					count++;
					if(count == maxLine){
						pages.add(strPage);
						count = 0;
						strPage = "";
					}
				}
			}
			
			strPage +="\n";
			if(count == maxLine){
				pages.add(strPage);
				count = 0;
				strPage = "";
			}
		}
		if(strPage.length() >0){
			pages.add(strPage);
			count = 0;
			strPage = "";
		}
		Log.d("TrungTT","max line:"+maxLine);
		return pages;
	}
}
